package com.gasolinator.a.util.persistence;

import android.content.Context;
import android.provider.Settings;
import android.telephony.TelephonyManager;

import java.lang.reflect.Method;

/**
 * Created by IntelliJ IDEA.
 * User: root
 * Date: 6/21/11
 * Time: 8:17 AM
 * To change this template use File | Settings | File Templates.
 */
public class DeviceIdGenerator implements IDeviceIdGenerator
{

    private static final String GASOLINATOR_ID_PREFIX ="0001";
    public static final String CANNOT_IDENTIFY_DEVICE="CANNOT_IDENTIFY_DEVICE";
    private static final String SERIAL_NUMBER_PREFIX="SN-";
    private static final String ANDROID_ID_PREFIX="AI-";
    private static final String TELEPHONY_ID_PREFIX="TI-";
    private Context baseContext;

    public DeviceIdGenerator(Context baseContext) {this.baseContext=baseContext;}
    public DeviceIdGenerator() {};

    @Override
    public String generate()
    {
        String deviceId=getSerialNo();
        if (!isEmpty(deviceId)) return returnAsSerialNumber(deviceId);
        deviceId=getAndroidId();
        if (!isEmpty(deviceId)) return returnAsAndroidId(deviceId);
        deviceId=getTelephonyId();
        if (!isEmpty(deviceId)) return returnAsTelephonyId(deviceId);
        return CANNOT_IDENTIFY_DEVICE;
    }

    private String returnAsTelephonyId(String deviceId)
    {
        return TELEPHONY_ID_PREFIX+signDeviceIdWithSemantixPrefix(deviceId);
    }

    private String returnAsAndroidId(String deviceId)
    {
        return ANDROID_ID_PREFIX+signDeviceIdWithSemantixPrefix(deviceId);
    }

    private String returnAsSerialNumber(String deviceId)
    {
        return SERIAL_NUMBER_PREFIX+signDeviceIdWithSemantixPrefix(deviceId);
    }

    private boolean isEmpty(String deviceId) {return (deviceId==null)||(deviceId.equals(""));}

    private String signDeviceIdWithSemantixPrefix(String deviceId)
    {
        String prefix= GASOLINATOR_ID_PREFIX;
        return prefix+deviceId;
    }

    public String getAndroidId()
    {
        return Settings.Secure.getString(baseContext.getContentResolver(), Settings.Secure.ANDROID_ID);
    }

    public String getTelephonyId()
    {
        TelephonyManager telephonyManager=(TelephonyManager) baseContext.getSystemService(baseContext.TELEPHONY_SERVICE);
        return telephonyManager.getDeviceId();
    }

    public String getSerialNo()
    {
        String serial=null;
        try
        {
            Class<?> c=Class.forName("android.os.SystemProperties");
            Method get=c.getMethod("get", String.class);
            serial=(String) get.invoke(c, "ro.serialno");
            return serial;

        }
        catch(Exception ignored)
        {
            System.out.println(ignored.getMessage());
            return "";
        }
    }
}
